package com.zheng.api.server.service.task;

import com.zheng.api.common.constant.ApiBaseResult;
import com.zheng.api.common.constant.ApiResultConstant;
import com.zheng.api.server.service.ApiServerUmbrellaService;
import com.zheng.business.common.constant.BusinessConstant;
import com.zheng.business.dao.model.*;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaConsumptionService;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaDepositService;
import com.zheng.business.rpc.api.BusinessOrderUmbrellaTimecardService;
import com.zheng.common.constant.PayConstant;
import com.zheng.common.util.DateUtil;
import com.zheng.upms.rpc.api.UpmsSystemParamService;
import com.zheng.wechat.mp.dao.model.WechatMpSystemAccount;
import com.zheng.wechat.mp.dao.model.WechatMpSystemAccountExample;
import com.zheng.wechat.mp.rpc.api.WechatMpSystemAccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 自动结算超过指定天数不归还雨伞订单，直接结算订单并扣除预付金(小于等于0则不启用)
 */
@Service
public class TimeoutOrderAutoCloseTaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TimeoutOrderAutoCloseTaskService.class);

    @Autowired
    UpmsSystemParamService upmsSystemParamService;
    @Autowired
    WechatMpSystemAccountService wechatMpSystemAccountService;
    @Autowired
    BusinessOrderUmbrellaConsumptionService businessOrderUmbrellaConsumptionService;
    @Autowired
    BusinessOrderUmbrellaDepositService businessOrderUmbrellaDepositService;
    @Autowired
    ApiServerUmbrellaService apiServerUmbrellaService;
    @Autowired
    BusinessOrderUmbrellaTimecardService businessOrderUmbrellaTimecardService;

    public ApiBaseResult doBusinessOrderCloseTask(String bDates){
        LOGGER.debug("AutoBusinessOrderCloseTask begin：{}", DateUtil.getDate());
        try {
            //自动结算超过指定天数不归还雨伞订单，结算扣费按照个性规则结算(填入金额大于0时，按照填入金额扣费,否则全额扣除预付金或失效年卡）。
            Date endTime = DateUtil.getNowDate();
            //查询超时未归还的借伞订单
            BusinessOrderUmbrellaConsumptionExample orderExample = new BusinessOrderUmbrellaConsumptionExample();
            BusinessOrderUmbrellaConsumptionExample.Criteria orderCriteria = orderExample.createCriteria();
            //借伞成功
            orderCriteria.andStatusEqualTo(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_3);
            //自动结算时间小于当前时间,大于指定天数的时间
            int days = 100;
            try {
                days = Integer.parseInt(bDates);
                if (days <= 0) {
                    days = 100;
                }
            }catch (Exception e){}

            Date beginTime = DateUtil.adddays(endTime, 0 - days);
            orderCriteria.andAutoendtimeGreaterThanOrEqualTo(beginTime);

            orderCriteria.andAutoendtimeLessThanOrEqualTo(endTime);
            orderCriteria.andAutoendtimeIsNotNull();
            orderCriteria.andAgentidIsNotNull();
            List<BusinessOrderUmbrellaConsumption> orderList = businessOrderUmbrellaConsumptionService.selectByExample(orderExample);
            //逐笔结算订单
            for (int i = 0; i < orderList.size(); i++) {
                BusinessOrderUmbrellaConsumption order = orderList.get(i);
                completeTimeoutBusinessOrderUmbrellaConsumption(order);
            }
        }catch (Exception e){
            LOGGER.error("AutoBusinessOrderCloseTask error",e);
        }
        LOGGER.debug("AutoBusinessOrderCloseTask end：{}", DateUtil.getDate());
        return new ApiBaseResult(ApiResultConstant.SUCCESS,null);
    }
    /**
     * 结算订单
     * @param orderNo
     * @return
     */
    @Async("threadPoolTaskExecutor")
    private void completeTimeoutBusinessOrderUmbrellaConsumption(BusinessOrderUmbrellaConsumption consumption){
        if(consumption==null){return ;}

        Date endTime = DateUtil.getDate();
        /**
         * 查询用户账号
         */
        WechatMpSystemAccountExample accountExample = new WechatMpSystemAccountExample();
        accountExample.createCriteria().andUserIdEqualTo(consumption.getUserid());
        WechatMpSystemAccount wechatMpSystemAccount = wechatMpSystemAccountService.selectFirstByExample(accountExample);

        if(wechatMpSystemAccount == null) return;
        /**
         * 更新用户账号
         */
        WechatMpSystemAccount updateAccount = new WechatMpSystemAccount();
        updateAccount.setDeposit(new BigDecimal(0));
        int number = wechatMpSystemAccount.getUmbrellanumber() - 1;
        if(number<0){number = 0 ;}
        updateAccount.setUmbrellanumber(number);
        wechatMpSystemAccountService.updateByExampleSelective(updateAccount,accountExample);

        /**
         * 更新订单
         */
        BigDecimal costDecimal = wechatMpSystemAccount.getDeposit();
        BigDecimal zero = new BigDecimal(0);
        //预付金金额大于零就扣预付金
        if(costDecimal.compareTo(zero) >= 0) {
            //预付金支付
            BusinessOrderUmbrellaConsumption updateConsumption = new BusinessOrderUmbrellaConsumption();
            updateConsumption.setEndtime(endTime);
            updateConsumption.setRentamount(costDecimal);
            updateConsumption.setPayamount(costDecimal);
            updateConsumption.setDiscountedamount(new BigDecimal(0));
            updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_6);
            updateConsumption.setPaymethod(PayConstant.PAY_METHOD_11);
            updateConsumption.setDescription("预付金支付");
            //更新订单
            BusinessOrderUmbrellaConsumptionExample consumptionExample = new BusinessOrderUmbrellaConsumptionExample();
            BusinessOrderUmbrellaConsumptionExample.Criteria consumptionCriteria = consumptionExample.createCriteria();
            consumptionCriteria.andOrdernoEqualTo(consumption.getOrderno());
            apiServerUmbrellaService.updateBusinessOrderUmbrellaConsumption(updateConsumption, consumptionExample);

            /**
             * 查询预付金订单
             */
            BusinessOrderUmbrellaDepositExample depositExample = new BusinessOrderUmbrellaDepositExample();
            BusinessOrderUmbrellaDepositExample.Criteria depositCriteria = depositExample.createCriteria();
            depositCriteria.andUseridEqualTo(wechatMpSystemAccount.getUserId());
            //业务处理完成
            depositCriteria.andStatusEqualTo(3);
            //未退款（状态为空）
            depositCriteria.andRefundstatusIsNull();
            BusinessOrderUmbrellaDeposit businessOrderUmbrellaDeposit = businessOrderUmbrellaDepositService.selectFirstByExample(depositExample);
            if (businessOrderUmbrellaDeposit != null) {
                /**
                 * 更新预付金订单为业务处理完成
                 */
                BusinessOrderUmbrellaDepositExample depositExample2 = new BusinessOrderUmbrellaDepositExample();
                BusinessOrderUmbrellaDepositExample.Criteria depositCriteria2 = depositExample2.createCriteria();
                depositCriteria2.andOrdernoEqualTo(businessOrderUmbrellaDeposit.getOrderno());
                BusinessOrderUmbrellaDeposit updateDeposit2 = new BusinessOrderUmbrellaDeposit();
                updateDeposit2.setRefundstatus(PayConstant.REFUND_STATUS_COMPLETE & 0xFF);
                businessOrderUmbrellaDepositService.updateByExampleSelective(updateDeposit2, depositExample2);
            }

        }else {
            Date nowDate = DateUtil.getDate();
            boolean isDifference = false;
            try{
                isDifference = "true".equals(upmsSystemParamService.querySystemParamValueByParam_key("BUSINESS_ORDER_TIMECARD_SETTLE_DIFF_AGENT"));
            }catch(Exception e){}
            //用户购买的对应订单代理的时长卡
            BusinessOrderUmbrellaTimecard latestTimeCard =  apiServerUmbrellaService.baseSelectLastBusinessOrderUmbrellaTimecardNoCache(consumption.getUserid(),consumption.getAgentid(),isDifference);
            //已购买时长卡还没到期
            if(latestTimeCard!=null && latestTimeCard.getCardAfterEndtime()!=null && latestTimeCard.getCardAfterEndtime().after(nowDate)){
                //年卡支付
                BusinessOrderUmbrellaConsumption updateConsumption = new BusinessOrderUmbrellaConsumption();
                updateConsumption.setEndtime(endTime);
                updateConsumption.setRentamount(zero);
                updateConsumption.setPayamount(zero);
                updateConsumption.setDiscountedamount(new BigDecimal(0));
                updateConsumption.setStatus(BusinessConstant.UM_CONSUMPTION_ORDER_STATUS_6);
                updateConsumption.setPaymethod(PayConstant.PAY_METHOD_13);
                updateConsumption.setDescription("时长卡支付");
                //更新订单
                BusinessOrderUmbrellaConsumptionExample consumptionExample = new BusinessOrderUmbrellaConsumptionExample();
                BusinessOrderUmbrellaConsumptionExample.Criteria consumptionCriteria = consumptionExample.createCriteria();
                consumptionCriteria.andOrdernoEqualTo(consumption.getOrderno());
                apiServerUmbrellaService.updateBusinessOrderUmbrellaConsumption(updateConsumption, consumptionExample);

                //更新时长卡为失效
                BusinessOrderUmbrellaTimecard updateTimecard = new BusinessOrderUmbrellaTimecard();
                updateTimecard.setStatus(PayConstant.PAY_STATUS_EXPIRED & 0xFF);
                updateTimecard.setDescription("借伞超时，已被失效。");
                BusinessOrderUmbrellaTimecardExample timecardExample = new BusinessOrderUmbrellaTimecardExample();
                BusinessOrderUmbrellaTimecardExample.Criteria  timecardCriteria = timecardExample.createCriteria();
                timecardCriteria.andOrdernoEqualTo(latestTimeCard.getOrderno());
                businessOrderUmbrellaTimecardService.updateByExampleSelective(updateTimecard,timecardExample);

            }
        }
    }
}
